package com.tiantianyuegou.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.R;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.ShopMemberInfo;
import com.tiantianyuegou.util.DateUtil;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.NetworkUtils;
import com.tiantianyuegou.util.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 我的会员界面
 * Created by Administrator on 2016/1/19.
 */
public class MyVipAvtivity extends BaseActivity implements View.OnClickListener {
    PullToRefreshListView list_my_vip;
    TextView mDateStart, mDateEnd;
    LinearLayout lay_starttime, lay_endtime, lay_serch;
    String startDate, starDatecp, endDate, endDatecp;
    private ImageView img_title;
    private TextView text_title;
    List<ShopMemberInfo> mMemberInfoList;
    MyVipAdapter adapter;
    private boolean isRefresh = true;
    private boolean isLoadmore = false;
    int mPage = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_vip);
        initViews();
    }

    @Override
    public void findViewByIds() {

        text_title = (TextView) findViewById(R.id.text_title);
        img_title = (ImageView) findViewById(R.id.img_title);
        text_title.setText("我的会员");
        img_title.setOnClickListener(this);
        list_my_vip = (PullToRefreshListView) findViewById(R.id.list_my_vip);
        lay_starttime = (LinearLayout) findViewById(R.id.lay_starttime);
        lay_endtime = (LinearLayout) findViewById(R.id.lay_endtime);
        mDateStart = (TextView) findViewById(R.id.tv_starttime);
        mDateEnd = (TextView) findViewById(R.id.tv_endtime);
        lay_serch = (LinearLayout) findViewById(R.id.lay_serch);

        list_my_vip.setVisibility(View.GONE);

        loadingDialog = new LoadingDialog(MyVipAvtivity.this);
        mMemberInfoList = new ArrayList<>();
        adapter = new MyVipAdapter();
        list_my_vip.setMode(PullToRefreshBase.Mode.BOTH);
        list_my_vip.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                isRefresh = true;
                isLoadmore = false;
                list_my_vip.setMode(PullToRefreshBase.Mode.BOTH);
                doMyVip(mDateStart.getText().toString(), mDateEnd.getText().toString(), mPage);
//                    isRefresh = true;
//                    isLoadmore = false;
//                    list_my_vip.setMode(PullToRefreshBase.Mode.BOTH);
//                    doMyVip(starDatecp, endDatecp, mPage);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                isRefresh = false;
                isLoadmore = true;
                doMyVip(starDatecp, endDatecp, (++mPage));
            }
        });

    }

    @Override
    public void initListener() {
        lay_starttime.setOnClickListener(this);
        lay_endtime.setOnClickListener(this);
        lay_serch.setOnClickListener(this);
    }

    @Override
    public void initData() {

        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);

//        mDateStart.setText(year + "-" + (month + 1) + "-" + day);
//        mDateEnd.setText(year + "-" + (month + 1) + "-" + (day + 1));

        starDatecp = DateUtil.getFormateDate2(year, month + 1, day);
        endDatecp = DateUtil.getFormateDate2(year, month + 1, day + 1);
        startDate = DateUtil.getFormateDate(year, month + 1, day);
        endDate = DateUtil.getFormateDate(year, month + 1, day + 1);
        list_my_vip.setVisibility(View.VISIBLE);
//        list_my_vip.setMode(PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
        doMyVip("", "", mPage);//调会员信息接口

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.lay_starttime:

                final Calendar cal = Calendar.getInstance();
                Dialog dialog = new DatePickerDialog(this,
                        AlertDialog.THEME_DEVICE_DEFAULT_LIGHT,
                        new DatePickerDialog.OnDateSetListener() {

                            @Override
                            public void onDateSet(DatePicker view, int year,
                                                  int monthOfYear, int dayOfMonth) {
                                mDateStart.setText(year + "-" + (monthOfYear + 1)
                                        + "-" + dayOfMonth);
                                startDate = DateUtil.getFormateDate(year,
                                        monthOfYear + 1, dayOfMonth);
                                starDatecp = DateUtil.getFormateDate2(year,
                                        monthOfYear + 1, dayOfMonth);
                                if (Integer.valueOf(endDatecp) <= Integer
                                        .valueOf(starDatecp) && !TextUtils.isEmpty(mDateStart.getText().toString()) && !TextUtils.isEmpty(mDateEnd.getText().toString())) {
                                    Toast.makeText(MyVipAvtivity.this, "查询日期必须小于终止日期", Toast.LENGTH_SHORT).show();
                                    mDateStart.setText("");

                                }
                            }
                        }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
                        cal.get(Calendar.DAY_OF_MONTH));
                dialog.show();
                break;
            case R.id.lay_endtime:
                final Calendar cal1 = Calendar.getInstance();
                Dialog dialog1 = new DatePickerDialog(this,
                        AlertDialog.THEME_DEVICE_DEFAULT_LIGHT,
                        new DatePickerDialog.OnDateSetListener() {

                            @Override
                            public void onDateSet(DatePicker view, int year,
                                                  int monthOfYear, int dayOfMonth) {
                                mDateEnd.setText(year + "-" + (monthOfYear + 1)
                                        + "-" + dayOfMonth);
                                endDate = DateUtil.getFormateDate(year,
                                        monthOfYear + 1, dayOfMonth);
                                endDatecp = DateUtil.getFormateDate2(year,
                                        monthOfYear + 1, dayOfMonth);
                                if (Integer.valueOf(endDatecp) <= Integer
                                        .valueOf(starDatecp) && !TextUtils.isEmpty(mDateStart.getText().toString()) && !TextUtils.isEmpty(mDateEnd.getText().toString())) {
                                    Toast.makeText(MyVipAvtivity.this, "查询日期必须大于起始日期", Toast.LENGTH_SHORT).show();

                                    mDateEnd.setText("");
                                }

                            }
                        }, cal1.get(Calendar.YEAR), cal1.get(Calendar.MONTH),
                        cal1.get(Calendar.DAY_OF_MONTH));
                dialog1.show();


                break;
            case R.id.lay_serch:
                isRefresh = true;
                isLoadmore = false;
                mPage = 1;
                if (TextUtils.isEmpty(mDateStart.getText().toString()) || TextUtils.isEmpty(mDateEnd.getText().toString())) {
                    showMsg("请选择查询时间");
                    mMemberInfoList.clear();
                    adapter.notifyDataSetChanged();
                    list_my_vip.setVisibility(View.GONE);
                    return;
                }
                list_my_vip.setVisibility(View.VISIBLE);
                loadingDialog.showDialog();
                loadingDialog.setMsg("正在加载");
                doMyVip(mDateStart.getText().toString(), mDateEnd.getText().toString(), mPage);
                break;
            case R.id.img_title:
                finish();
                break;
        }
    }


    private LoadingDialog loadingDialog;

    /**
     * 调我的会员信息接口
     */
    private void doMyVip(String startDate, String endDate, int page) {
        if (!NetworkUtils.isNetworkAvailable(MyVipAvtivity.this)) {
            MyVipAvtivity.this.showMsg("请检查网络");
            return;
        }
        RequestParams params = new RequestParams();
        String tsId = SPHelper.getTSId();
        System.out.println("-----------" + tsId);
        params.addBodyParameter("tsId", tsId);
        params.addBodyParameter("startDate", startDate);
        params.addBodyParameter("endDate", endDate);
        params.addBodyParameter("page", "" + page);

        loadData(HttpRequest.HttpMethod.POST, ApiDefine.STORE_MEMBER_LIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                System.out.println(responseInfo.result);
                loadingDialog.dismiss();
                list_my_vip.onRefreshComplete();
                String root = responseInfo.result;

                try {
                    JSONObject rootObj = new JSONObject(root);
                    String code = rootObj.getString("code");
                    if (code.equalsIgnoreCase("100")) {
                        if (isRefresh) {
                            isRefresh = false;
                            mMemberInfoList.clear();
                        }
                        if (isLoadmore) {
                            isLoadmore = false;
                        }
                        String list = rootObj.getString("list");
                        JSONArray listArray = new JSONArray(list);
                        for (int i = 0; i < listArray.length(); i++) {
                            JSONObject temp = listArray.getJSONObject(i);
                            String tmId = temp.getString("tmId");
                            String tmName = temp.getString("tmName");
                            String tmPhone = temp.getString("tmPhone");
                            String tmRedCount = temp.getString("tmRedCount");
                            ShopMemberInfo memberInfo = new ShopMemberInfo(tmId, tmName, tmPhone, tmRedCount);
                            mMemberInfoList.add(memberInfo);
                        }
                        adapter.notifyDataSetChanged();
                        list_my_vip.setAdapter(adapter);
                    } else if (code.equalsIgnoreCase("104") && !isLoadmore) {
                        showMsg("没有更多会员信息");
                        mMemberInfoList.clear();
                        list_my_vip.setVisibility(View.GONE);
                        adapter.notifyDataSetChanged();
                        if (isRefresh) {
                            isRefresh = false;
                        }

                    } else {
                        list_my_vip.setMode(PullToRefreshBase.Mode.PULL_DOWN_TO_REFRESH);
                        showMsg("没有更多会员信息");
                        if (isRefresh) {
                            isRefresh = false;
                        }
                        if (isLoadmore) {
                            isLoadmore = false;
                            mPage--;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    if (isRefresh) {
                        isRefresh = false;
                    }
                    if (isLoadmore) {
                        isLoadmore = false;
                        mPage--;
                    }
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                list_my_vip.onRefreshComplete();
               ToastUtils.showToast(MyVipAvtivity.this, "请求服务器失败");
                loadingDialog.dismiss();
                if (isRefresh) {
                    isRefresh = false;
                }
                if (isLoadmore) {
                    isLoadmore = false;
                    mPage--;
                }
            }
        });
    }


    class MyVipAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mMemberInfoList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int position, View view, ViewGroup viewGroup) {
            ViewHolder holder = null;
            if (view == null) {
                view = LayoutInflater.from(MyVipAvtivity.this).inflate(R.layout.list_item_myvip, null);
                holder = new ViewHolder();
                holder.tv_item_viphone = (TextView) view.findViewById(R.id.tv_item_viphone);
                holder.tv_item_vipname = (TextView) view.findViewById(R.id.tv_item_vipname);
                holder.tv_item_viprednum = (TextView) view.findViewById(R.id.tv_item_viprednum);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            String name = mMemberInfoList.get(position).getTmName();
            if (name.length() > 3) {
                holder.tv_item_vipname.setText(name.substring(0,3)+"...");
            } else {
                holder.tv_item_vipname.setText(name);
            }
            String mPhonenum = mMemberInfoList.get(position).getTmPhone();
            holder.tv_item_viphone.setText(mPhonenum.substring(0, 3) + "****" + mPhonenum.substring(7));
            holder.tv_item_viprednum.setText(mMemberInfoList.get(position).getTmRedCount());
            adapter.notifyDataSetChanged();
            return view;
        }

        class ViewHolder {
            TextView tv_item_vipname, tv_item_viphone, tv_item_viprednum;
        }
    }
}
